import type { ProxyOptions } from 'vite'

type ProxyTargetList = Record<string, ProxyOptions & { rewrite: (path: string) => string }>
const httpsReg = /^https:\/\//

export function createProxy(proxyDescription: Array<[string, string]>): ProxyTargetList {
  const proxy: ProxyTargetList = {}
  for (const [prefix, target] of proxyDescription) {
    if (prefix in proxy) {
      continue
    }
    const isHttps = httpsReg.test(prefix)
    proxy[prefix] = {
      target: target,
      changeOrigin: true,
      ws: true,
      rewrite: path => path.replace(new RegExp(`^${prefix}`), ''),
      ...(isHttps ? { secure: false } : {})
    }
  }

  return proxy
}
